<template>
  <!-- 游戏区域 -->
  <div class="game-box">
    <div class="title"> 成语小游戏 </div>
    <div v-if="gameInfo && gameInfo.idiom">
      <div> 第{{ gameInfo.level }}关 </div>

      <div>
        <span>{{ gameInfo.idiom.substring(0, gameInfo.index) }}_{{ gameInfo.idiom.substring(gameInfo.index) }}</span>
      </div>
      <div>
        <el-button size="large" type="primary" v-for="d in gameInfo.results.split('')" @click="getGameResult(d)">{{ d }}</el-button>
      </div>
      <div>
        <el-progress type="circle" :stroke-width="10" :percentage="percentage">
          <template #default>
            <span>{{ timeout }}</span>
          </template>
        </el-progress>
      </div>
      <!-- {{ gameInfo }}
      <br /> -->
      <div v-if="!gameSuccess && gameResult && gameResult.explanation">
        正确答案：{{ gameResult.word }}/{{ gameResult.pinyin }}
        <br />
        <div>{{ gameResult.explanation }}</div>
      </div>
    </div>
    <div>
      <el-button size="large" type="primary" @click="getGameInfo"> {{ gametitle }} </el-button>
    </div>
  </div>
  <!-- 排行榜 -->
  <div class="rank-box">
    <GameRankComp game="idiom"></GameRankComp>
  </div>

  <BackToHome></BackToHome>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ApiService as api } from '../../ts/ApiService'
import { IdiomGame, TbDataIdiom } from '../../ts/types/Game'
import { BaseDataResult } from '../../ts/types/BaseResult'
import { ElMessage, ElMessageBox } from 'element-plus'
import { log } from '../../ts/logger'
import GameRankComp from '../../components/GameRankComp.vue'
import BackToHome from '../../components/BackToHomeComp.vue'

//#region 游戏相关
const gametitle = ref('开始游戏')

const gaming_key = 'idiom.gaming'
const gaming = ref(false)
gaming.value = sessionStorage.getItem(gaming_key) == 'true'

const setGaming = () => {
  sessionStorage.setItem(gaming_key, 'true')
}

const removeGaming = () => {
  sessionStorage.removeItem(gaming_key)
}

const gameInfo = ref<IdiomGame>()
gameInfo.value = {} as IdiomGame

const getGameInfo = () => {
  setGaming()
  gameResult.value = {} as TbDataIdiom
  gameInfo.value = {} as IdiomGame
  api.get('/games/idiom', {}, (data: BaseDataResult<IdiomGame>) => {
    if (data.success) {
      severerTime.value = data.data.now
      timeout.value = data.data.limit
      percentage.value = 100
      startTimer()
      gameInfo.value = data.data
      gametitle.value = '下一关'
    } else {
      ElMessage.error(data.message)
      removeGaming()
    }
  })
}

const gameResult = ref<TbDataIdiom>()
const gameSuccess = ref(false)

gameResult.value = {} as TbDataIdiom

const getGameResult = (answer: string) => {
  stopTimer()
  gameResult.value = {} as TbDataIdiom
  api.post('/games/idiom', { answer: answer }, (data: BaseDataResult<TbDataIdiom>) => {
    gameResult.value = data.data
    gameSuccess.value = data.success
    if (data.success) {
      gametitle.value = '下一关'
      ElMessage.success(data.message)
    } else {
      removeGaming()
      gametitle.value = '重新开始'
      ElMessage.error(data.message)
    }
  })
}

const resetGame = () => {
  gametitle.value = '重新开始'
  gameInfo.value = {} as IdiomGame
  gameResult.value = {} as TbDataIdiom
}

const timer = ref<number>()
const severerTime = ref(0)
const percentage = ref(100)
const timeout = ref(0)

const startTimer = () => {
  timer.value = setInterval(() => {
    if (gameInfo.value && gameInfo.value.timeout) {
      timeout.value = Math.floor((gameInfo.value.timeout - severerTime.value) / 1000)
      percentage.value = Math.floor((timeout.value / gameInfo.value.limit) * 100)
      severerTime.value = severerTime.value + 1000
      log.debug('超时计算：', timeout, gameInfo.value.timeout, severerTime.value)
      if (timeout.value <= 0) {
        stopTimer()
        removeGaming()
        ElMessageBox.alert('游戏超时').then(resetGame).catch(resetGame)
      }
    }
  }, 1000)
}

const stopTimer = () => {
  clearInterval(timer.value)
}

//#endregion

//#region 页面挂载
onMounted(() => {
  if (gaming.value) {
    getGameInfo()
  }
})

onUnmounted(() => {
  if (timer.value) {
    log.debug('清除计时器任务')
    clearInterval(timer.value)
  }
})
//#endregion
</script>

<style lang="scss" scoped>
.game-box {
  text-align: center;
  div {
    padding: 1rem 0px;
  }
  .title {
    font-size: 2rem;
    font-weight: bold;
  }
}
.rank-box {
  position: fixed;
  right: 1rem;
  top: 1rem;
}
</style>
